package org.catspaw.cherubim.persistence.jdbc.transaction;

import java.sql.Connection;
import java.sql.SQLException;

import org.catspaw.cherubim.persistence.TransactionException;
import org.catspaw.cherubim.persistence.TransactionManager;
import org.catspaw.cherubim.persistence.jdbc.ConnectionManager;

public class JdbcTransactionManager implements TransactionManager {

	private ConnectionManager	connectionManager;

	public JdbcTransactionManager(ConnectionManager connectionManager) {
		this.connectionManager = connectionManager;
	}

	public void beginTransaction() throws TransactionException {
		Connection conn;
		try {
			conn = connectionManager.getConnection();
		} catch (SQLException e) {
			throw new TransactionException(e);
		}
		try {
			conn.setAutoCommit(false);
		} catch (SQLException e) {
			throw new TransactionException(e);
		}
	}

	public boolean inTransaction() throws TransactionException {
		Connection conn;
		try {
			conn = connectionManager.getCurrentConnection();
		} catch (SQLException e) {
			throw new TransactionException(e);
		}
		try {
			if (conn != null && !conn.getAutoCommit()) {
				return true;
			}
		} catch (SQLException e) {
			throw new TransactionException(e);
		}
		return false;
	}

	public void commit() throws TransactionException {
		Connection conn;
		try {
			conn = connectionManager.getCurrentConnection();
		} catch (SQLException e) {
			throw new TransactionException(e);
		}
		if (conn == null) {
			throw new IllegalStateException(
					"current thread is no connection in transaction");
		}
		try {
			conn.commit();
		} catch (SQLException e) {
			throw new TransactionException(e);
		}
	}

	public void rollback() throws TransactionException {
		Connection conn;
		try {
			conn = connectionManager.getCurrentConnection();
		} catch (SQLException e) {
			throw new TransactionException(e);
		}
		if (conn == null) {
			throw new IllegalStateException(
					"current thread is no connection in transaction");
		}
		try {
			conn.rollback();
		} catch (SQLException e) {
			throw new TransactionException(e);
		}
	}
	
	public ConnectionManager getConnectionManager() {
		return connectionManager;
	}
}
